package stu.sup.controller.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import stu.sup.entity.UserInfo;
import stu.sup.entity.UserLogin;
import stu.sup.service.IUserInfoService;
import stu.sup.service.IUserLoginService;
import stu.sup.util.JsonResult;
import stu.sup.util.Sha256Utils;

import javax.servlet.http.HttpServletRequest;

/**
 * 本类用来演示：
 *
 * @author:Administrator
 * @data:2020/7/3 0003
 */
@Controller
public class RegisterController {

    @Autowired
    private IUserLoginService userLoginService;

    @Autowired
    private IUserInfoService userInfoService;

    @RequestMapping("register")
    public String register(){
        return "/view/register";
    }

    @PostMapping("/view/register")
    @ResponseBody
    public JsonResult register(String username,String password,String telephone,Integer kinds,HttpServletRequest request) {
        System.out.println("输入的用户名:" + username);
        System.out.println("输入的密码:" + password);
        System.out.println("输入的电话:" + telephone);
        System.out.println("选择的类型：" + kinds);

        //验证用户名是否已经被注册
        JsonResult jsonResult = userLoginService.getByUsername(username);
        JsonResult jsonResult1 = new JsonResult();

        if (jsonResult.getCode() == 0) {
            System.out.println("用户名已存在,不可注册");
            jsonResult1 =  new JsonResult(2, "注册失败",null);
        } else {
            //创建登录的各个参数
            UserLogin userLogin = new UserLogin();
            userLogin.setUsername(username);
            userLogin.setPassword(password);
            userLogin.setTelephone(telephone);

            //判断注册的是商家还是用户端
            if (kinds == 1) {
                userLogin.setStatus("1");
            }else {
                userLogin.setStatus("0");
            }
            int row = userLoginService.register(userLogin);
//            System.out.println(row);


            if (row == 1) {
                jsonResult1 = new JsonResult(0, "注册成功", row);
//                System.out.println(userLogin.getId());

                //注册成功时在user-info 表中插入个人信息
                UserInfo userInfo = new UserInfo();
                userInfo.setUserLoginId(userLogin.getId());
                userInfo.setPhone(userLogin.getTelephone());
                userInfoService.save(userInfo);
            } else {
                jsonResult1 = new JsonResult(1, "注册失败", row);
            }
        }

        return jsonResult1;
    }

    @RequestMapping("merchant")
    public String merchant(){
        return "/view/merchant";
    }
}